from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView

from cart.cartser import CartSerializer
from cart.models import CartModel
from order.models import UserCoupon, OrderModel, OrderDetailModel, MyCourseModel
from order.orderser import UserCouponSerializer, OrderSerializer, OrderDetailSerializer, MyCourseSerializer
from user.models import UserModel
from utils.Alipay import AliPaySDK
from utils.authorization import MyAuthentication
from utils.myredis import redis_toll
from django.db import transaction


# Create your views here.


class CartView(ListAPIView):
    queryset = CartModel.objects.all()
    serializer_class = CartSerializer

    authentication_classes = [MyAuthentication]

    def get_queryset(self):
        user = self.request.query_params.get('user')
        if user:
            return self.queryset.filter(user=user, select=True)


class CouponView(APIView):
    authentication_classes = [MyAuthentication]

    def get(self, request):
        user = request.query_params.get('user')
        userinfo = UserModel.objects.filter(id=user).first()
        mycoupon = UserCoupon.objects.filter(user=user)
        ser = UserCouponSerializer(instance=mycoupon, many=True)
        return Response({"message": "ok", "data": {"credit": userinfo.credit, "tomoney": 10}, 'coupon': ser.data})


def get_order_no():
    import time
    import random
    order_number = str(time.strftime('%Y%m%d%H%M%S')) + str(random.randint(1000, 9999))
    return order_number


class Order(APIView):
    authentication_classes = [MyAuthentication]

    def post(self, request):
        user = request.data.get('user')
        order = redis_toll.get_str(user)
        if order:
            return Response({"code": 400, "message": "订单已存在,请勿重复提交"})
        # 开启事务,保存点
        transac = transaction.savepoint()
        try:
            order_data = {
                "order_no": get_order_no(),
                "user": user,
                "score": request.data.get('score', 0),
                "coupon": request.data.get('coupon', None),
                "pay_type": request.data.get('pay_type', 1),
            }
            # 总价获取
            cart = CartModel.objects.filter(user=user, select=True)
            total_price = 0
            for i in cart:
                total_price += i.course.discount
            order_data["total_price"] = total_price
            order_data["pay_price"] = total_price
            # 实付价格
            if order_data["score"] != 0:
                order_data["pay_price"] = float(order_data["total_price"]) - order_data["score"] / 10
            if order_data["coupon"] is not None:
                cou = UserCoupon.objects.filter(id=order_data["coupon"]).first()
                if cou.is_show:
                    order_data["pay_price"] = order_data["total_price"] - cou.coupon.price

            order_ser = OrderSerializer(data=order_data)
            # 订单号存入redis
            redis_toll.set_string(user, order_data['order_no'])
            if order_ser.is_valid():
                order_ser.save()
                for i in cart:
                    detail = {
                        "order": order_ser.data.get('id'),
                        "course": i.course.id,
                        "price": i.course.price,
                        "discount": i.course.discount,
                        "cover": 'http://127.0.0.1:8000/uploads' + str(i.course.cover),
                        "c_name": i.course.c_name
                    }
                    detail_ser = OrderDetailSerializer(data=detail)
                    if detail_ser.is_valid():
                        detail_ser.save()
                    else:
                        return Response(detail_ser.errors)
                    i.delete()
            else:
                return Response(order_ser.errors)
            # 移除redis数据
            redis_toll.del_string(user)
            transaction.savepoint_commit(transac)
            return Response({"message": "订单生成成功", "id": order_ser.data.get('id'), 'timeout': 30})
        except:
            # 事务的回滚点
            transaction.savepoint_rollback(transac)
            return Response({"message": "订单生成失败"})


class AliPayLink(APIView):
    authentication_classes = [MyAuthentication]

    def get(self, request):
        oid = request.query_params.get('order')
        order = OrderModel.objects.filter(id=oid).first()
        if order:
            ali = AliPaySDK()
            return Response(ali.page_pay(order.order_no, order.pay_price, '向浮光付款'))
        else:
            return Response({"message": "订单不存在"})


class AliPayResult(APIView):
    def get(self, request):
        ali = AliPaySDK()
        result = ali.check_sign(request.query_params.dict())
        if result:
            order = OrderModel.objects.filter(order_no=request.query_params.get('out_trade_no')).first()
            order.status = 1
            order.pay_no = request.query_params.get('trade_no')
            order.pay_time = request.query_params.get('timestamp')
            order.save()
            # 是否使用积分
            if order.score:
                user = UserModel.objects.filter(id=order.user.id).first()
                user.credit = user.credit - order.score
                user.save()
            # 是否使用优惠券
            if order.coupon:
                coupon = UserCoupon.objects.filter(id=order.coupon).first()
                coupon.is_show = False
                coupon.save()
            # 返回给用户数据
            course = OrderDetailModel.objects.filter(order=order.id)
            ser = OrderDetailSerializer(course, many=True)
            # 将课程信息存储到我的课程中
            for i in course:
                my_data = {
                    "user": order.user.id,
                    "course": i.course.id,
                    "c_name": i.course.c_name,
                    "price": i.course.price,
                    "discount": i.course.discount,
                    "cover": 'http://127.0.0.1:8000/uploads' + str(i.course.cover),
                }
                my_ser = MyCourseSerializer(data=my_data)
                if my_ser.is_valid():
                    my_ser.save()
                else:
                    return Response({"message": my_ser.errors})
            return Response(
                {"message": "支付成功", "course": ser.data, "pay_time": order.pay_time, "pay_price": order.pay_price})
        else:
            return Response({"message": "支付失败"})


class MyCourseView(APIView):
    authentication_classes = [MyAuthentication]

    def get(self, request):
        user = request.query_params.get('user')
        info = MyCourseModel.objects.filter(user=user)
        ser = MyCourseSerializer(instance=info, many=True)
        return Response({"message": "ok", "data": ser.data})


class Pagination(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'size'
    page_query_param = 'page'


class MyOrderView(ListAPIView):
    queryset = OrderModel.objects.all()
    serializer_class = OrderSerializer
    pagination_class = Pagination
    authentication_classes = [MyAuthentication]

    def get_queryset(self):
        user = self.request.query_params.get('user')
        status = self.request.query_params.get('status')
        if int(status) == -1:
            return self.queryset.filter(user=user)
        else:
            return self.queryset.filter(user=user, status=status)


class StatusView(APIView):
    def get(self, request):
        return Response([
            {'id': 0, 'name': '待支付'},
            {'id': 1, 'name': '已支付'},
            {'id': 2, 'name': '已取消'},
            {'id': 3, 'name': '已完成'},
        ])
